package com.qdxwx.web.controller.ajax;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.course.CourseNodeService;
import com.qdxwx.data.service.course.CourseNoteService;
import com.qdxwx.models.course.CourseNode;
import com.qdxwx.models.course.CourseNote;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/ajax/course/note")
public class AjaxCourseNoteController extends BaseController {

    @Autowired
    private CourseNoteService courseNoteService;
    @Autowired
    private CourseNodeService courseNodeService;

    /**
     * 查询该用户笔记
     */
    @RequestMapping("/query.json")
    @ResponseBody
    public AjaxResult queryNote(HttpServletRequest request, @RequestParam(value = "nodeId", defaultValue = "0") int nodeId) {
        long userId = LoginUser.getUserId(request);
        //通过节点id和用户id查询笔记
        CourseNote courseNote = courseNoteService.getCourseNote(userId, nodeId);
        if (courseNote == null) {
            courseNote = new CourseNote();
        }
        return AjaxResult.success(TKString.isEmpty(courseNote.getContent())?courseNote.getContent():"");
    }

    /**
     * 添加笔记
     */
    @RequestMapping("/add.json")
    @ResponseBody
    public AjaxResult addNote(HttpServletRequest request) {
        String content = request.getParameter("content");
        if (TKString.isEmpty(content)) return AjaxResult.error("保存笔记不能为空");
        int nodeId = TKConvert.toInteger(request.getParameter("nodeId"));
        if (nodeId < 1) return AjaxResult.error("章节id错误");
        CourseNode courseNode = courseNodeService.get(nodeId);
        if (courseNode == null) return AjaxResult.error("找不到指定章节");
        CourseNote courseNote = new CourseNote();
        courseNote.setContent(content);
        courseNote.setNodeId(courseNode.getNodeId());
        courseNote.setCourseId(courseNode.getCourseId());
        courseNote.setUserId(LoginUser.getUserId(request));
        int count = courseNoteService.insert(courseNote);
        return count > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}